<?php

namespace App\Http\Controllers\Member;

use App\CustomTrait\StatusReturnTrait;
use App\Model\MaterielPhone;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class MaterielPhoneController extends CommonController
{
  use StatusReturnTrait;

  /**
   * 首页
   * @param Request $request
   * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
   */
  public function index(Request $request)
  {
    session(['materiel_id' => $request->get('mp')]);
    return view('member.materiel.phone.index');
  }

  /**
   * 创建物料号码
   * @param MaterielPhone $materielPhone
   * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
   */
  public function create(MaterielPhone $materielPhone)
  {
    return view('member.materiel.phone.create', compact('materielPhone'));
  }

  /**
   * 物料号码入库
   * @param Request $request
   * @return mixed
   */
  public function store(Request $request)
  {
    $data = [
        'phone' => $request->get('param')['phone'],
        'member_id' => getMemberId(),
        'materiel_id' => $this->getMaterielId()
    ];
    try {
      DB::beginTransaction();
      MaterielPhone::create($data);
      DB::commit();
      return $this->success(route('materielPhone.index', ['mp' => $this->getMaterielId()]), '提交成功');
    } catch (\Exception $error) {
      return $this->error('error', '提交失败,请联系客服或者管理员');
    }
  }

  /**
   * 编辑页面
   * @param $id
   * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
   */
  public function edit($id)
  {
    $materielPhone = MaterielPhone::whereId($id)->first();
    return view('member.materiel.phone.edit', compact('materielPhone'));
  }

  /**
   * 编辑信息入库
   * @param $id
   * @param Request $request
   * @return \Illuminate\Http\JsonResponse
   */
  public function update($id, Request $request)
  {
    try {
      DB::beginTransaction();
      MaterielPhone::whereId($id)->update($request->get('param'));
      DB::commit();
      return $this->success(route('materielPhone.index', ['mp' => $this->getMaterielId()]), '提交成功');
    } catch (\Exception $error) {
      return $this->error('error', '提交失败,请联系客服或者管理员');
    }
  }

  /**
   * 物料号码删除
   * @param $id
   * @return \Illuminate\Http\JsonResponse
   */
  public function destroy($id)
  {
    try {
      DB::beginTransaction();
      MaterielPhone::whereId($id)->where('member_id', getMemberId())->delete();
      DB::commit();
      return $this->success('success', '删除成功');
    } catch (\Exception $error) {
      return $this->error('error', '删除失败,请联系客服或者管理员');
    }
  }

  /**
   * 获取数据列表
   * @return \Illuminate\Http\JsonResponse
   */
  public function getLayUiTableData(Request $request)
  {
    $filter = $request->all();
    return MaterielPhone::LayUiTableData($filter, getMemberId());
  }
}
